<template>
  <div style="user-select: none">
    <!-- <div>
      <span>用户饮食问卷已填写，点击</span>
      <a-button type="link" style="padding-left: 0" @click="getDietQuestion">查看详情</a-button>
    </div> -->
    <a-form
      ref="manaPlanFormRef"
      class="mana-plan-form"
      :label-col="{ style: { width: '90px' } }"
      :disabled="isPushed"
      :model="updatedData"
    >
      <template v-if="updatedData.length">
        <div class="mana-plan-item-info">
          <a-form-item label="当前模板库">
            <div style="display: flex; align-items: center; justify-content: space-between">
              <div style="display: flex; align-content: center">
                <a-space :size="[0, 0]">
                  <span
                    @click="changeTemplate(updatedData[0], '公共模板')"
                    :class="
                      updatedData[0].templateAffiliation == '公共模板'
                        ? 'template-col template-col-active'
                        : 'template-col'
                    "
                    >饮食方案模板库</span
                  >
                  <span
                    @click="changeTemplate(updatedData[0], '个人模板')"
                    :class="
                      updatedData[0].templateAffiliation == '个人模板'
                        ? 'template-col template-col-active'
                        : 'template-col'
                    "
                    >个人模板库</span
                  >
                  <span
                    @click="changeTemplate(updatedData[0], 'AI生成')"
                    :class="
                      updatedData[0].templateAffiliation == 'AI生成'
                        ? 'template-col template-col-active'
                        : 'template-col'
                    "
                    >AI生成</span
                  >
                </a-space>
              </div>
            </div>
          </a-form-item>
          <div v-for="(item, index) in updatedData" :key="index">
            <div
              class="mana-plan-time"
              @click="item.onShowTask = !item.onShowTask"
              v-if="item.templateAffiliation == 'AI生成' && item.cycleStart"
            >
              <template v-if="item.onShowTask">
                <CaretDownOutlined />
              </template>
              <template v-else>
                <CaretRightOutlined />
              </template>
              <span class="time-label">
                {{ dayjs(item.cycleStart).format('YYYY/MM/DD') }}
                -
                {{ dayjs(item.cycleEnd).format('YYYY/MM/DD') }}
              </span>
              <a-tag
                v-if="item.pushStatus == '待推送'"
                style="color: #f53f3f; background-color: #ffece8; border-color: #f53f3f"
                >待推送</a-tag
              >
              <a-tag
                v-if="item.pushStatus == '已推送'"
                style="color: #00b42a; background-color: #e8ffea; border-color: #00b42a"
                >已推送</a-tag
              >
              <a-tag v-if="item.pushStatus == '未推送'">未推送</a-tag>
            </div>
            <template v-if="item.onShowTask || item.templateAffiliation != 'AI生成'">
              <div :class="['mana-plan-task', item.cycleStart ? 'mana-plan-ai' : '']">
                <div
                  v-if="
                    item.templateAffiliation == 'AI生成' &&
                    (item.pushStatus == '待推送' || !item.pushStatus)
                  "
                  style="display: flex; align-items: center"
                >
                  <template v-if="item.aiStatus == 30">
                    <img class="ai-state-icon" src="@/assets/health/ai-error.png" alt="" />
                  </template>
                  <template v-if="!item.aiStatus || item.aiStatus == 20 || item.aiStatus == 10">
                    <img class="ai-state-icon" src="@/assets/health/ai-normal.png" alt="" />
                  </template>
                  <span>{{ item.aiCodeLabel }}</span>
                  <a-button
                    type="primary"
                    @click="regenerate(item)"
                    style="margin-left: 12px"
                    v-if="!item.aiStatus || item.aiStatus == 30"
                  >
                    {{ transformAISattus(item) }}
                  </a-button>
                  <template v-if="item.aiStatus == 40">
                    <div style="display: flex; align-items: center; margin-left: 12px">
                      <img
                        style="width: 16px; height: 16px"
                        src="@/assets/health/loading.png"
                        alt=""
                      />
                      <a-button type="link" @click="regenerate(item)" style="padding-left: 8px">
                        重新生成
                      </a-button>
                    </div>
                  </template>

                  <a-button
                    type="primary"
                    v-if="item.aiStatus == 40"
                    @click="showAiDetail(item, index)"
                  >
                    查看AI生成方案
                  </a-button>
                </div>
                <!-- 模板选择 -->
                <template v-if="item.templateAffiliation != 'AI生成'">
                  <a-form-item label="选择模板" :rules="[{ required: true, message: '选择模板' }]">
                    <a-select
                      v-model:value="item.templateId"
                      placeholder="请选择模板"
                      :options="item.templateList"
                      @change="templateChange(item, $event, index)"
                      showSearch
                    />

                    <a-button type="link" @click="showIndividual(item)"
                      >保存当前已修改方案到个人模板</a-button
                    >
                  </a-form-item>
                </template>
                <!-- 模板选择 -->
                <a-divider
                  style="margin: 12px 0"
                  v-if="
                    item.pushStatus == '待推送' ||
                    !item.pushStatus ||
                    item.templateAffiliation != 'AI生成'
                  "
                />
                <!-- 内容 -->
                <div>
                  <div class="season-row" v-if="item.templateAffiliation != 'AI生成'">
                    <template v-if="item.content">
                      <span
                        :class="['season-item', secindex === seasonKey ? 'season-item-active' : '']"
                        v-for="(seasonItem, secindex) in item.content.seasons"
                        :key="secindex"
                        @click="seasonChange(secindex, index)"
                      >
                        {{ seasonLabel[seasonItem.season] }}
                      </span>
                    </template>
                  </div>

                  <div
                    class="week-row"
                    v-if="item.content && item.content.seasons && item.content.seasons.length"
                  >
                    <div
                      v-for="(weekItem, weekIndex) in item.content.seasons[seasonKey].week"
                      :key="weekIndex"
                    >
                      <span
                        @click="weekChange(index, weekIndex)"
                        :class="[
                          'week-item',
                          weekIndex === item.activeKey ? 'week-item-active' : ''
                        ]"
                      >
                        <template v-if="item.templateAffiliation == 'AI生成'">
                          第{{ weekDay[weekItem.day - 1] }}天
                        </template>
                        <template v-else> {{ weekLabel[weekItem.day - 1] }}食谱 </template>
                      </span>
                      <a-divider
                        style="margin-right: 13px"
                        v-if="weekIndex !== item.content.seasons[seasonKey].week.length - 1"
                        type="vertical"
                      />
                    </div>
                  </div>
                  <div v-if="item.content && item.content.seasons && item.content.seasons.length">
                    <p class="diet-info-box">
                      食谱详情：
                      <span class="diet-info diet-all">
                        总摄入
                        <span :class="['diet-all', getFoodInfoStatus('energy', index)]">
                          {{ getFoodInfo('energy', index) }}
                        </span>
                        /推荐{{ numberToFixedEnergy(recommendEnergy) || '--' }}千卡
                      </span>
                      <span class="diet-info">
                        碳水
                        <span :class="[getFoodInfoStatus('cho', index)]">{{
                          getFoodInfo('cho', index)
                        }}</span>
                        /推荐{{ numberToFixed(recommendCho) || '--' }}g
                      </span>
                      <span class="diet-info">
                        蛋白质
                        <span :class="[getFoodInfoStatus('pro', index)]">{{
                          getFoodInfo('pro', index)
                        }}</span>
                        /推荐{{ numberToFixed(recommendPro) || '--' }}g
                      </span>
                      <span class="diet-info">
                        脂肪
                        <span :class="[getFoodInfoStatus('fat', index)]">{{
                          getFoodInfo('fat', index)
                        }}</span>
                        /推荐{{ numberToFixed(recommendFat) || '--' }}g
                      </span>
                    </p>

                    <a-form-item label="早餐" :labelCol="{ style: { width: '70px' } }" required>
                      <div class="dict-group">
                        <template
                          v-if="
                            item.content &&
                            item.content.seasons &&
                            item.content.seasons.length &&
                            item.content.seasons[seasonKey].week
                          "
                        >
                          <div
                            class="dict-name"
                            v-for="(diet, dietIndex) in item.content.seasons[seasonKey]?.week[
                              item.activeKey
                            ]?.itemContent.breakfast.food_items"
                            :key="dietIndex"
                          >
                            <template v-if="diet.ingredients">
                              <span>
                                <!-- {{ diet.name }} -->
                                <span
                                  class="food-sub-name"
                                  v-for="(subDiet, subDietIndex) in diet.ingredients"
                                  :key="subDietIndex"
                                >
                                  {{ subDiet.name }}
                                  （
                                  <span
                                    class="food-weight"
                                    @click="
                                      showDict('breakfast', 'edit', index, dietIndex, subDietIndex)
                                    "
                                  >
                                    {{ (Number(subDiet.amount) * (subDiet.ratio || 1)).toFixed(0) }}
                                  </span>
                                  g）
                                </span>
                              </span>
                            </template>

                            <CloseOutlined
                              class="dict-del-icon"
                              @click="delDict('breakfast', dietIndex, index)"
                              v-if="!isPushed && !getDayDisabled(item)"
                            />
                          </div>
                        </template>
                        <div
                          class="dict-btn"
                          @click="showDict('breakfast', 'add', index)"
                          v-if="!isPushed && !getDayDisabled(item)"
                        >
                          新增
                          <PlusOutlined class="icon-add" />
                        </div>
                      </div>
                    </a-form-item>

                    <a-form-item label="早加餐" :labelCol="{ style: { width: '70px' } }">
                      <div class="dict-group">
                        <template
                          v-if="
                            item.content &&
                            item.content.seasons &&
                            item.content.seasons.length &&
                            item.content.seasons[seasonKey].week
                          "
                        >
                          <div
                            class="dict-name"
                            v-for="(diet, dietIndex) in item.content.seasons[seasonKey]?.week[
                              item.activeKey
                            ]?.itemContent.breakfast_plus.food_items"
                            :key="dietIndex"
                          >
                            <template v-if="diet.ingredients">
                              <span>
                                <!-- {{ diet.name }} -->
                                <span
                                  class="food-sub-name"
                                  v-for="(subDiet, subDietIndex) in diet.ingredients"
                                  :key="subDietIndex"
                                >
                                  {{ subDiet.name }}
                                  （

                                  <span
                                    class="food-weight"
                                    @click="
                                      showDict(
                                        'breakfast_plus',
                                        'edit',
                                        index,
                                        dietIndex,
                                        subDietIndex
                                      )
                                    "
                                  >
                                    {{ (Number(subDiet.amount) * (subDiet.ratio || 1)).toFixed(0) }}
                                  </span>
                                  g）
                                </span>
                              </span>
                            </template>

                            <CloseOutlined
                              class="dict-del-icon"
                              @click="delDict('breakfast_plus', dietIndex, index)"
                              v-if="!isPushed && !getDayDisabled(item)"
                            />
                          </div>
                        </template>
                        <span
                          class="dict-btn"
                          @click="showDict('breakfast_plus', 'add', index)"
                          v-if="!isPushed && !getDayDisabled(item)"
                        >
                          新增
                          <PlusOutlined class="icon-add" />
                        </span>
                      </div>
                    </a-form-item>

                    <a-form-item label="午餐" :labelCol="{ style: { width: '70px' } }" required>
                      <div class="dict-group">
                        <template
                          v-if="
                            item.content &&
                            item.content.seasons &&
                            item.content.seasons.length &&
                            item.content.seasons[seasonKey].week
                          "
                        >
                          <div
                            class="dict-name"
                            v-for="(diet, dietIndex) in item.content.seasons[seasonKey]?.week[
                              item.activeKey
                            ]?.itemContent.lunch.food_items"
                            :key="dietIndex"
                          >
                            <template v-if="diet.ingredients">
                              <span>
                                <!-- {{ diet.name }} -->
                                <span
                                  class="food-sub-name"
                                  v-for="(subDiet, subDietIndex) in diet.ingredients"
                                  :key="subDietIndex"
                                >
                                  {{ subDiet.name }}
                                  （

                                  <span
                                    class="food-weight"
                                    @click="
                                      showDict('lunch', 'edit', index, dietIndex, subDietIndex)
                                    "
                                  >
                                    {{ (Number(subDiet.amount) * (subDiet.ratio || 1)).toFixed(0) }}
                                  </span>
                                  g）
                                </span>
                              </span>
                            </template>

                            <CloseOutlined
                              class="dict-del-icon"
                              @click="delDict('lunch', dietIndex, index)"
                              v-if="!isPushed && !getDayDisabled(item)"
                            />
                          </div>
                        </template>
                        <span
                          class="dict-btn"
                          @click="showDict('lunch', 'add', index)"
                          v-if="!isPushed && !getDayDisabled(item)"
                        >
                          新增
                          <PlusOutlined class="icon-add" />
                        </span>
                      </div>
                    </a-form-item>

                    <a-form-item label="午加餐" :labelCol="{ style: { width: '70px' } }">
                      <div class="dict-group">
                        <template
                          v-if="
                            item.content &&
                            item.content.seasons &&
                            item.content.seasons.length &&
                            item.content.seasons[seasonKey].week
                          "
                        >
                          <div
                            class="dict-name"
                            v-for="(diet, dietIndex) in item.content.seasons[seasonKey]?.week[
                              item.activeKey
                            ]?.itemContent.lunch_plus.food_items"
                            :key="dietIndex"
                          >
                            <template v-if="diet.ingredients">
                              <span>
                                <!-- {{ diet.name }} -->
                                <span
                                  class="food-sub-name"
                                  v-for="(subDiet, subDietIndex) in diet.ingredients"
                                  :key="subDietIndex"
                                >
                                  {{ subDiet.name }}
                                  （

                                  <span
                                    class="food-weight"
                                    @click="
                                      showDict('lunch_plus', 'edit', index, dietIndex, subDietIndex)
                                    "
                                  >
                                    {{ (Number(subDiet.amount) * (subDiet.ratio || 1)).toFixed(0) }}
                                  </span>
                                  g）
                                </span>
                              </span>
                            </template>

                            <CloseOutlined
                              class="dict-del-icon"
                              @click="delDict('lunch_plus', dietIndex, index)"
                              v-if="!isPushed && !getDayDisabled(item)"
                            />
                          </div>
                        </template>
                        <span
                          class="dict-btn"
                          @click="showDict('lunch_plus', 'add', index)"
                          v-if="!isPushed && !getDayDisabled(item)"
                        >
                          新增
                          <PlusOutlined class="icon-add" />
                        </span>
                      </div>
                    </a-form-item>

                    <a-form-item label="晚餐" :labelCol="{ style: { width: '70px' } }" required>
                      <div class="dict-group">
                        <template
                          v-if="
                            item.content &&
                            item.content.seasons &&
                            item.content.seasons.length &&
                            item.content.seasons[seasonKey].week
                          "
                        >
                          <div
                            class="dict-name"
                            v-for="(diet, dietIndex) in item.content.seasons[seasonKey]?.week[
                              item.activeKey
                            ]?.itemContent.dinner.food_items"
                            :key="dietIndex"
                          >
                            <template v-if="diet.ingredients">
                              <span>
                                <!-- {{ diet.name }} -->
                                <span
                                  class="food-sub-name"
                                  v-for="(subDiet, subDietIndex) in diet.ingredients"
                                  :key="subDietIndex"
                                >
                                  {{ subDiet.name }}
                                  （

                                  <span
                                    class="food-weight"
                                    @click="
                                      showDict('dinner', 'edit', index, dietIndex, subDietIndex)
                                    "
                                  >
                                    {{ (Number(subDiet.amount) * (subDiet.ratio || 1)).toFixed(0) }}
                                  </span>
                                  g）
                                </span>
                              </span>
                            </template>

                            <CloseOutlined
                              class="dict-del-icon"
                              @click="delDict('dinner', dietIndex, index)"
                              v-if="!isPushed && !getDayDisabled(item)"
                            />
                          </div>
                        </template>
                        <span
                          class="dict-btn"
                          @click="showDict('dinner', 'add', index)"
                          v-if="!isPushed && !getDayDisabled(item)"
                        >
                          新增
                          <PlusOutlined class="icon-add" />
                        </span>
                      </div>
                    </a-form-item>

                    <a-form-item label="晚加餐" :labelCol="{ style: { width: '70px' } }">
                      <div class="dict-group">
                        <template
                          v-if="
                            item.content &&
                            item.content.seasons &&
                            item.content.seasons.length &&
                            item.content.seasons[seasonKey].week
                          "
                        >
                          <div
                            class="dict-name"
                            v-for="(diet, dietIndex) in item.content.seasons[seasonKey]?.week[
                              item.activeKey
                            ]?.itemContent.dinner_plus.food_items"
                            :key="dietIndex"
                          >
                            <template v-if="diet.ingredients">
                              <span>
                                <!-- {{ diet.name }} -->
                                <span
                                  class="food-sub-name"
                                  v-for="(subDiet, subDietIndex) in diet.ingredients"
                                  :key="subDietIndex"
                                >
                                  {{ subDiet.name }}
                                  （

                                  <span
                                    class="food-weight"
                                    @click="
                                      showDict(
                                        'dinner_plus',
                                        'edit',
                                        index,
                                        dietIndex,
                                        subDietIndex
                                      )
                                    "
                                  >
                                    {{ (Number(subDiet.amount) * (subDiet.ratio || 1)).toFixed(0) }}
                                  </span>
                                  g）
                                </span>
                              </span>
                            </template>

                            <CloseOutlined
                              class="dict-del-icon"
                              @click="delDict('dinner_plus', dietIndex, index)"
                              v-if="!isPushed && !getDayDisabled(item)"
                            />
                          </div>
                        </template>
                        <span
                          class="dict-btn"
                          @click="showDict('dinner_plus', 'add', index)"
                          v-if="!isPushed && !getDayDisabled(item)"
                        >
                          新增
                          <PlusOutlined class="icon-add" />
                        </span>
                      </div>
                    </a-form-item>
                  </div>
                </div>
                <!-- 内容 -->
              </div>
            </template>
          </div>
        </div>
      </template>

      <!-- <a-button
        @click="addPlanItem"
        :icon="h(PlusOutlined)"
        type="primary"
        ghost
        v-if="!isPushed && updatedData.length == 0"
        class="add-plan-item"
      >
        添加
      </a-button> -->
    </a-form>

    <!-- 个人模板保存 -->
    <a-modal
      v-model:open="individualOpen"
      title="保存当前方案到个人模板"
      :maskClosable="false"
      :destroyOnClose="true"
    >
      <a-form ref="individualForm" :model="individualFormData" style="margin-top: 14px">
        <div style="margin-bottom: 16px; font-weight: bold">{{ individualName }}</div>
        <a-form-item
          name="templateName"
          :rules="[{ required: true, message: '请输入模板名称', whitespace: true }]"
        >
          <a-auto-complete
            style="width: 100%"
            placeholder="请输入模板名称"
            :options="individualTemplateList"
            v-model:value="individualFormData.templateName"
            :filter-option="filterOption"
            @blur="
              (value) => {
                individualFormData.templateName = individualFormData.templateName.replace(
                  /\s+/g,
                  ''
                )
              }
            "
          />
          <span
            v-if="
              individualTemplateList.findIndex((item) => {
                return item.value === individualFormData.templateName
              }) >= 0
            "
            style="color: red"
            >您当前选择的是已存在的模板，保存将覆盖原有模板内容</span
          >
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button @click="individualOpen = false">取消</a-button>
        <a-button type="primary" @click="saveIndividual">保存</a-button>
      </template>
    </a-modal>

    <!-- 选择食谱 -->
    <a-modal
      width="800px"
      v-model:open="dietOpen"
      :title="!dietFormDisable ? '添加食物' : '修改食物'"
      :maskClosable="false"
      ok-text="确认"
      cancel-text="取消"
    >
      <a-form :label-col="{ style: { width: '80px' } }" :model="dietForm" ref="dietFormRef">
        <a-form-item label="选择食物" name="foodName" required>
          <a-select
            v-model:value="dietForm.foodName"
            showSearch
            :options="dietDictData"
            style="width: 100%"
            placeholder="食物名称"
            :listHeight="200"
            allowClear
            :disabled="dietFormDisable"
            @change="dietChange"
            option-label-prop="label"
          >
            <template #option="{ label, energy, cho, fat, pro }">
              {{ label }}
              <span v-if="energy || cho || pro || fat" style="font-size: 12px; color: #666">
                每100克：热量{{ energy }}千卡、碳水{{ cho }}克、蛋白质{{ pro }}克、脂肪{{ fat }}克
              </span>
            </template>
          </a-select>
        </a-form-item>
        <a-form-item label="食物重量" name="amount" required>
          <div style="display: flex; align-items: center; justify-content: space-between">
            <a-input-number
              v-model:value="dietForm.amount"
              :min="0"
              step="0.1"
              :precision="1"
              style="width: 100%"
            />
          </div>
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button
          @click="
            () => {
              ;(dietOpen = false), dietFormRef.clearValidate()
            }
          "
        >
          取消
        </a-button>
        <a-button type="primary" @click="dietConfirm">确认</a-button>
      </template>
    </a-modal>

    <AiDetail ref="aiDetailRef" @setPlan="setAiPlan" />
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, h, defineEmits, watchEffect } from 'vue'
import {
  PlusOutlined,
  CloseOutlined,
  CaretDownOutlined,
  CaretRightOutlined
} from '@ant-design/icons-vue'
import store from '@/store'
import {
  getAiCycleTask,
  getTemplateDetailList,
  TemplateAddOrUpdate
} from '@/api/healthManaWorkbench/index'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import {
  getAiRecommendScheme,
  getAiRecommendSchemeDetail,
  getPatientRecommendIntake
} from '@/api/healthManaWorkbench/index'
import AiDetail from './AiDetail.vue'
const manaPlanFormRef = ref()
const props = defineProps<{
  isPushed: boolean
  empi: string
  diseaseType: string
  serviceState: string
}>()

const defineModelData = defineModel<any>('dietData', { default: () => [] })
const updatedData = computed({
  get() {
    return defineModelData.value
  },
  set(val) {
    defineModelData.value = val
  }
})

const seasonLabel = reactive<any>({
  spring: '春季',
  summer: '夏季',
  fall: '秋季',
  winter: '冬季'
})
const weekDay = reactive<any>(['一', '二', '三', '四', '五', '六', '七'])
const weekLabel = reactive<any>(['周一', '周二', '周三', '周四', '周五', '周六', '周日'])

const seasonsData = reactive([
  {
    season: 'spring',
    week: [
      {
        day: 1,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      },
      {
        day: 2,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      },
      {
        day: 3,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      },
      {
        day: 4,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      },
      {
        day: 5,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      },
      {
        day: 6,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      },
      {
        day: 7,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      }
    ]
  },
  {
    season: 'summer',
    week: [
      {
        day: 1,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      },
      {
        day: 2,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      },
      {
        day: 3,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      },
      {
        day: 4,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      },
      {
        day: 5,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      },
      {
        day: 6,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      },
      {
        day: 7,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      }
    ]
  },
  {
    season: 'fall',
    week: [
      {
        day: 1,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      },
      {
        day: 2,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      },
      {
        day: 3,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      },
      {
        day: 4,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      },
      {
        day: 5,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      },
      {
        day: 6,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      },
      {
        day: 7,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      }
    ]
  },
  {
    season: 'winter',
    week: [
      {
        day: 1,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      },
      {
        day: 2,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      },
      {
        day: 3,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      },
      {
        day: 4,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      },
      {
        day: 5,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      },
      {
        day: 6,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      },
      {
        day: 7,
        itemContent: {
          breakfast: {
            food_items: []
          },
          breakfast_plus: {
            food_items: []
          },
          lunch: {
            food_items: []
          },
          lunch_plus: {
            food_items: []
          },
          dinner: {
            food_items: []
          },
          dinner_plus: {
            food_items: []
          }
        }
      }
    ]
  }
])

const recommendEnergy = ref<number>(0)
const recommendCho = ref<number>(0)
const recommendPro = ref<number>(0)
const recommendFat = ref<number>(0)

const numberToFixed = (num: any) => {
  return Number(num).toFixed(1)
}

const numberToFixedEnergy = (num: any) => {
  return Number(num).toFixed(0)
}

const dietDictData = ref()
const userId = ref()
const templateDataList = ref()
const dietOpen = ref(false)

// 模板
const individualTemplateList = ref()
const individualOpen = ref<boolean>(false)
const individualName = ref<string>('')
const individualFormData = reactive({
  templateName: '',
  templateType: '',
  content: '',
  data: {}
})

const emit = defineEmits(['update:dietData'])
const seasonKey = ref(0)

// const updatedData = ref<any>([])
onMounted(async () => {
  dietDictData.value = store.userApp.dietDictList
  userId.value = store.userApp.userInfo.id
  seasonKey.value = 0
  templateDataList.value = await getTemplateList(null, null)
  setTimeout(() => {
    getPatientRecommendIntake({ empi: props.empi }).then((res: any) => {
      if (res.data) {
        recommendEnergy.value = res.data.find((v: any) => v.extKey === 'energy')
          ? res.data.find((v: any) => v.extKey === 'energy').extValue
          : 0
        recommendCho.value = res.data.find((v: any) => v.extKey === 'cho')
          ? res.data.find((v: any) => v.extKey === 'cho').extValue
          : 0
        recommendPro.value = res.data.find((v: any) => v.extKey === 'pro')
          ? res.data.find((v: any) => v.extKey === 'pro').extValue
          : 0
        recommendFat.value = res.data.find((v: any) => v.extKey === 'fat')
          ? res.data.find((v: any) => v.extKey === 'fat').extValue
          : 0
      }
    })
    console.log(updatedData.value)
    if (
      updatedData.value &&
      updatedData.value[0] &&
      updatedData.value[0].templateAffiliation == 'AI生成'
    ) {
      getAiTask() // ai周期任务
    } else {
      updatedData.value.forEach((v: any) => {
        v.activeKey = 0
      })
    }
  }, 300)
})

const filterOption = (input: string, option: any) => {
  return option.value.toUpperCase().indexOf(input.toUpperCase()) >= 0
}

// 模板切换
const changeTemplate = (data, type) => {
  if (props.isPushed) {
    return
  } else {
    seasonKey.value = 0
    data.activeKey = 0
    if (data.templateAffiliation == type) {
      //
    } else {
      data.templateAffiliation = type
      if (type == 'AI生成') {
        getAiTask()
      } else {
        data.templateList = templateDataList.value.filter((tem) => {
          if (type == '个人模板') {
            return (
              tem.templateType == data.templateType &&
              tem.templateAffiliation == type &&
              tem.creator == userId.value
            )
          } else {
            return tem.templateType == data.templateType && tem.templateAffiliation == type
          }
        })
        if (type == '个人模板') {
          if (data.personTempId) {
            data.templateList.findIndex((ele) => {
              return ele.id == data.personTempId
            }) === -1 &&
              data.templateList.push({
                templateId: data.personTempId,
                templateName: data.personTempName,
                content: data.personTempContent,
                templateType: '饮食方案',
                templateAffiliation: '个人模板',
                creator: userId.value,
                label: data.templateName,
                value: data.personTempId,
                id: data.personTempId
              })
          }
        }

        if (data.oldTemplateAffiliation != type) {
          data.templateId = data.templateList.length > 0 ? data.templateList[0].id : undefined
        } else {
          data.templateId = data.oldTemeplateId
        }

        const temData: any = data.templateList.find((tem) => {
          return tem.id == data.templateId
        })
        data.content = temData ? temData.content : ''

        if (data.content) {
          const contentDiet = JSON.parse(data.content)
          data.content = contentDiet
        } else {
          data.content = {
            seasons: seasonsData
          }
        }

        data.cycleStart = null
        updatedData.value = [data]
      }
    }
  }
}

// 查询Ai生成的状态
const aiGenerateStatus = (data, type = true) => {
  return getAiRecommendScheme({
    empi: props.empi,
    code: 'DIET',
    diseaseType: props.diseaseType
  }).then((res: any) => {
    if (res.data) {
      data.aiStatus = res.data.status
      if (type) {
        const content = res.data.content ? JSON.parse(res.data.content) : ''
        data.AITaskData = content
        // data.content = content
        data.AIContent = content
      }
    } else {
      data.aiStatus = -1
    }
    transformAISattus(data)
  })
}

// 调用ai生成
const aiGenerateApi = (data: any) => {
  getAiRecommendSchemeDetail({
    empi: props.empi,
    code: 'DIET',
    diseaseType: props.diseaseType
  }).then(() => {
    data.aiStatus = 20

    transformAISattus(data)
  })
}

// 重新生成ai方案
const regenerate = (data: any) => {
  if ([30, 40].includes(data.aiStatus) || !data.aiStatus) {
    aiGenerateApi(data)
  }
}

const transformAISattus = (data: any) => {
  switch (data.aiStatus) {
    case 10:
      data.aiCodeLabel = '可通过AI大模型为用户生成饮食方案'
      return ''
    case 20:
      data.aiCodeLabel = '正在根据用户健康数据，生成AI饮食方案...'
      return ''
    case 30:
      data.aiCodeLabel = 'AI生成失败，请重新生成'
      return '重新生成'
    case 40:
      data.aiCodeLabel =
        data.pushStatus == '待推送'
          ? '以下方案由A依据用户健康数据和近一周饮食习惯生成，请审核确认'
          : '以下方案由AI依据用户健康数据生成，请审核确认'
      return ''
    default:
      data.aiCodeLabel = '可通过AI大模型为用户生成饮食方案'
      return 'AI生成'
  }
}

// 查看AI生成的周期任务
const getAiTask = () => {
  const params = {
    empi: props.empi,
    planType: 'DIET'
  }

  getAiCycleTask(params).then(async (res: any) => {
    const aitaskList: any = []

    if (res.data && res.data.length > 0) {
      res.data.forEach((item: any, index: number) => {
        const vo = {
          id: item.id,
          aiStatus: 40,
          AIContent: JSON.parse(item.modelContent),
          content: JSON.parse(item.modelContent),
          AITaskData: JSON.parse(item.modelContent),
          templateAffiliation: 'AI生成',
          templateType: '饮食方案',
          cycleStart: dayjs(item.cycleStart).format('YYYY-MM-DD'),
          cycleEnd: dayjs(item.cycleEnd).format('YYYY-MM-DD'),
          pushStatus: item.pushStatus,
          aiCodeLabel:
            item.pushStatus == '待推送'
              ? '以下方案由AI依据用户健康数据和近一周饮食习惯生成，请审核确认'
              : '',
          onShowTask: index ? false : true,
          activeKey: 0,
          oldTemeplateId: updatedData.value[0].oldTemeplateId,
          oldTemplateAffiliation: updatedData.value[0].oldTemplateAffiliation
        }
        aitaskList.push(vo)
      })

      const findIndex = aitaskList.findIndex((item) => item.pushStatus == '待推送')
      if (findIndex > -1) {
        await aiGenerateStatus(aitaskList[findIndex])
        updatedData.value = [...aitaskList]
        console.log(updatedData.value)
      } else {
        updatedData.value = [...aitaskList]
      }
    }

    if (aitaskList.length == 0 && updatedData.value.length == 0) {
      const mock = {
        templateAffiliation: 'AI生成',
        templateId: undefined,
        templateType: '饮食方案',
        content: {
          seasons: seasonsData
        },
        cycleStart: null,
        aiCodeLabel: '',
        onShowTask: true,
        pushStatus: null,
        activeKey: 0,
        aiStatus: -1
      }

      aitaskList.push(mock)
      await aiGenerateStatus(aitaskList[0])
      updatedData.value = [...updatedData.value, ...aitaskList]
    } else if (updatedData.value.length == 1) {
      if (updatedData.value[0].oldTemplateAffiliation != 'AI生成') {
        const mock = {
          templateAffiliation: 'AI生成',
          templateId: undefined,
          templateType: '饮食方案',
          content: {
            seasons: seasonsData
          },
          cycleStart: null,
          aiCodeLabel: '',
          onShowTask: true,
          pushStatus: null,
          activeKey: 0,
          aiStatus: -1,
          oldTemeplateId: updatedData.value[0].oldTemeplateId,
          oldTemplateAffiliation: updatedData.value[0].oldTemplateAffiliation
        }

        if (aitaskList.length > 0) {
          console.log(aitaskList[0])
          if (dayjs(aitaskList[0].cycleEnd).isBefore(dayjs())) {
            aitaskList.unshift(mock)
          }
        } else {
          aitaskList.unshift(mock)
        }
        await aiGenerateStatus(aitaskList[0])
        updatedData.value = [...aitaskList]
      } else {
        await aiGenerateStatus(updatedData.value[0])
        updatedData.value = [...updatedData.value]
      }
    } else {
      if (JSON.stringify(aitaskList[0].content) === '{}') {
        await aiGenerateStatus(aitaskList[0])
        updatedData.value = [...aitaskList]
      }
    }
  })
}

// 查看ai生成的方案
const aiDetailRef = ref()
const aiDetailIndex = ref()
const showAiDetail = (data: any, index: any) => {
  const res = JSON.parse(JSON.stringify(data.AITaskData))
  aiDetailIndex.value = index
  res.seasons.forEach((item: any) => {
    item.week.forEach((vo: any) => {
      if (typeof vo.itemContent === 'string') {
        vo.itemContent = JSON.parse(vo.itemContent)
      }
    })
  })
  res.seasons.forEach((item: any) => {
    if (item.week) {
      item.week.forEach((vo: any) => {
        if (!vo.itemContent.breakfast) {
          vo.itemContent.breakfast = {
            food_items: []
          }
        }
        if (!vo.itemContent.lunch) {
          vo.itemContent.lunch = {
            food_items: []
          }
        }
        if (!vo.itemContent.dinner) {
          vo.itemContent.dinner = {
            food_items: []
          }
        }
        if (!vo.itemContent.breakfast_plus) {
          vo.itemContent.breakfast_plus = {
            food_items: []
          }
        }
        if (!vo.itemContent.lunch_plus) {
          vo.itemContent.lunch_plus = {
            food_items: []
          }
        }
        if (!vo.itemContent.dinner_plus) {
          vo.itemContent.dinner_plus = {
            food_items: []
          }
        }
      })
    }
  })
  aiDetailRef.value.init(res, 'diet', {
    energy: recommendEnergy.value,
    cho: recommendCho.value,
    pro: recommendPro.value,
    fat: recommendFat.value
  })
}

// 使用ai方案
const setAiPlan = (data: any) => {
  updatedData.value[aiDetailIndex.value].content = data
}

const addPlanItem = () => {
  updatedData.value.push({
    templateAffiliation: '公共模板',
    templateId: undefined,
    templateType: '饮食方案',
    templateList: templateDataList.value.filter((tem) => {
      return tem.templateType == '饮食方案' && tem.templateAffiliation == '公共模板'
    }),
    content: {
      seasons: seasonsData
    }
  })

  // emit('update:dietData', updatedData.value)
}

// 选择模板切换
const templateChange = (data, e, index) => {
  seasonKey.value = 0
  data.activeKey = 0
  // 根据选择的模板更新内容
  const selectedTemplate = data.templateList.find((tem) => tem.id == e)
  data.content = selectedTemplate ? JSON.parse(selectedTemplate.content) : ''
  data.templateId = e
  updatedData.value[index] = { ...data }

  emit('update:dietData', updatedData.value)
}

// 展示个人模板保存
const showIndividual = (data) => {
  // 模板类型判断
  try {
    if (data.content.seasons) {
      data.content.seasons.forEach((item) => {
        item.week.forEach((vo) => {
          if (vo.itemContent.breakfast.food_items.length == 0) {
            message.error(`饮食方案请填写完整`)
            throw Error()
          }

          if (vo.itemContent.lunch.food_items.length == 0) {
            message.error(`饮食方案请填写完整`)
            throw Error()
          }

          if (vo.itemContent.dinner.food_items.length == 0) {
            message.error(`饮食方案请填写完整`)
            throw Error()
          }
        })
      })
    }
  } catch (error) {
    return
  }

  individualTemplateList.value = []
  nextTick(() => {
    individualOpen.value = true
    if (individualForm.value) {
      individualForm.value.resetFields()
    }
    individualFormData.templateName = ''
    individualName.value = '饮食方案个人模板库'
    individualFormData.templateType = '饮食方案'
    individualFormData.content = data.content
    individualFormData.data = data // 需要保存的模板数据
    const listData = templateDataList.value.filter((tem) => {
      return (
        tem.templateType == '饮食方案' &&
        tem.templateAffiliation == '个人模板' &&
        tem.creator == userId.value
      )
    })
    listData.forEach((item) => {
      individualTemplateList.value.push({
        value: item.templateName,
        label: item.templateName
      })
    })
  })
}

// 个人模板保存
const individualForm = ref()
const saveIndividual = () => {
  individualForm.value.validate().then(() => {
    // 对应模板类型的所有个人模板数据
    const templateData = templateDataList.value.filter((tem) => {
      return (
        tem.templateType == individualFormData.templateType &&
        tem.templateAffiliation == '个人模板' &&
        tem.creator == userId.value
      )
    })
    const temContent = individualFormData.data.content
    individualFormData.templateName = individualFormData.templateName.replace(/\s+/g, '')
    const data = {
      id: null,
      templateName: individualFormData.templateName,
      templateType: individualFormData.templateType,
      content: JSON.stringify(temContent),
      templateAffiliation: '个人模板',
      platformId: store.userStore.platformId
    }
    if (templateData.length > 0) {
      const someData = templateData.filter((item) => {
        return item.templateName === individualFormData.templateName
      })
      data.id = someData.length > 0 ? someData[0].id : null
    }

    TemplateAddOrUpdate(data).then(async (res) => {
      individualOpen.value = false
      templateDataList.value = await getTemplateList(null, null)
      updatedData.value.map((item) => {
        item.templateList = templateDataList.value.filter((tem) => {
          return (
            tem.templateType == individualFormData.templateType &&
            tem.templateAffiliation == '个人模板' &&
            tem.creator == userId.value
          )
        })

        item.templateList.findIndex((ele) => {
          return ele.templateId == item.personTempId
        }) === -1 &&
          item.templateList.push({
            templateId: item.personTempId,
            templateName: item.personTempName,
            content: item.personTempContent,
            templateType: '饮食方案',
            templateAffiliation: '个人模板',
            creator: userId.value,
            label: item.templateName,
            value: item.personTempId,
            id: item.personTempId
          })
      })
      message.success('保存成功')
      emit('update:dietData', updatedData.value)
    })
  })
}
// 根据方案类型 模板类型获取响应的列表
const getTemplateList = async (templateType, templateAffiliation) => {
  let data: any = []
  const res = await getTemplateDetailList({
    templateType: templateType,
    templateAffiliation: templateAffiliation,
    platformId: store.userStore.platformId
  })

  res.data.map((item: any) => {
    item.label = item.templateName
    item.value = item.id
  })
  data = res.data
  return data
}

const addFoodType = ref('')
const dietFormDisable = ref(false)
const dietTaskIndex = ref<any>()
const dietDayIndex = ref<any>()
const ingredientsIndex = ref<any>()

const dietFormRef = ref()
const dietForm = reactive({
  foodName: '',
  amount: 0,
  energy: 0,
  cho: 0,
  pro: 0,
  fat: 0
})
const showDict = (
  foodType: any,
  handleType: string,
  index: any,
  dietIndex?: any,
  subDietIndex?: any
) => {
  dietFormDisable.value = handleType === 'edit' ? true : false
  addFoodType.value = foodType
  if (!props.isPushed && !getDayDisabled(updatedData.value[index])) {
    dietOpen.value = true
    nextTick(() => {
      if (dietFormRef.value) {
        dietForm.foodName = ''
        dietForm.amount = 0
        dietForm.energy = 0
        dietForm.cho = 0
        dietForm.pro = 0
        dietForm.fat = 0
        dietTaskIndex.value = index
        dietDayIndex.value = dietIndex
        ingredientsIndex.value = subDietIndex

        if (dietIndex != undefined || dietIndex != null) {
          const diet =
            updatedData.value[index].content.seasons[seasonKey.value].week[
              updatedData.value[index].activeKey
            ].itemContent[foodType].food_items[dietIndex].ingredients[subDietIndex]

          dietForm.foodName = diet.name
          dietForm.amount = diet.amount * (diet.ratio || 1)
          dietForm.energy = diet.energy
          dietForm.cho = diet.cho
          dietForm.pro = diet.pro
          dietForm.fat = diet.fat
        }
      }
    })
  }
}

// 删除
const delDict = (foodType: any, dietIndex: any, index: any) => {
  updatedData.value[index].content.seasons[seasonKey.value].week[
    updatedData.value[index].activeKey
  ].itemContent[foodType].food_items.splice(dietIndex, 1)
}

// 食物选择
const dietChange = (item: any) => {
  dietDictData.value.map((vo: any) => {
    if (vo.options) {
      const selectDietData = vo.options.find((child: any) => child.label === item)
      if (selectDietData) {
        dietForm.foodName = selectDietData.label
        dietForm.energy = selectDietData.energy
        dietForm.cho = selectDietData.cho
        dietForm.pro = selectDietData.pro
        dietForm.fat = selectDietData.fat
      }
    }
  })
}

const dietConfirm = () => {
  dietFormRef.value
    .validate()
    .then(() => {
      if (dietFormDisable.value) {
        updatedData.value[dietTaskIndex.value].content.seasons[seasonKey.value].week[
          updatedData.value[dietTaskIndex.value].activeKey
        ].itemContent[addFoodType.value].food_items[dietDayIndex.value].ingredients[
          ingredientsIndex.value
        ] = {
          name: dietForm.foodName,
          amount: dietForm.amount,
          energy: dietForm.energy,
          cho: dietForm.cho,
          pro: dietForm.pro,
          fat: dietForm.fat
        }
      } else {
        updatedData.value[dietTaskIndex.value].content.seasons[seasonKey.value].week[
          updatedData.value[dietTaskIndex.value].activeKey
        ].itemContent[addFoodType.value].food_items.push({
          name: dietForm.foodName,
          ingredients: [
            {
              name: dietForm.foodName,
              amount: dietForm.amount,
              energy: dietForm.energy,
              cho: dietForm.cho,
              pro: dietForm.pro,
              fat: dietForm.fat
            }
          ]
        })
      }
      dietOpen.value = false
    })
    .catch((e) => {
      //
    })
}
// 四季切换
const seasonChange = (secindex: any, index: any) => {
  seasonKey.value = secindex
  updatedData.value[index].activeKey = 0
}

// 星期切换
const weekChange = (index: any, weekIndex: any) => {
  updatedData.value[index].activeKey = weekIndex
}

// 能量统计
const getFoodInfo = (type: any, index: any) => {
  if (
    updatedData.value &&
    updatedData.value.length > 0 &&
    updatedData.value[index].content &&
    updatedData.value[index].content.seasons &&
    updatedData.value[index].content.seasons.length &&
    updatedData.value[index].content.seasons[seasonKey.value].week &&
    updatedData.value[index].content.seasons[seasonKey.value].week.length
  ) {
    const data: any =
      updatedData.value[index].content.seasons[seasonKey.value].week[
        updatedData.value[index].activeKey
      ]?.itemContent

    let total: any = 0
    if (data) {
      data.breakfast.food_items.forEach((item) => {
        item.ingredients.forEach((child) => {
          if (child[type]) {
            total += foodTypeMash(child, type)
          }
        })
      })

      data.lunch.food_items.forEach((item) => {
        item.ingredients.forEach((child) => {
          if (child[type]) {
            total += foodTypeMash(child, type)
          }
        })
      })

      data.dinner.food_items.forEach((item) => {
        item.ingredients.forEach((child) => {
          if (child[type]) {
            total += foodTypeMash(child, type)
          }
        })
      })

      if (data.breakfast_plus) {
        data.breakfast_plus.food_items.forEach((item) => {
          item.ingredients.forEach((child) => {
            if (child[type]) {
              total += foodTypeMash(child, type)
            }
          })
        })
      }

      if (data.lunch_plus) {
        data.lunch_plus.food_items.forEach((item) => {
          item.ingredients.forEach((child) => {
            if (child[type]) {
              total += foodTypeMash(child, type)
            }
          })
        })
      }

      if (data.dinner_plus) {
        data.dinner_plus.food_items.forEach((item) => {
          item.ingredients.forEach((child) => {
            if (child[type]) {
              total += foodTypeMash(child, type)
            }
          })
        })
      }
    }

    if (type == 'energy') {
      return total ? total.toFixed(0) : '--'
    } else {
      return total ? total.toFixed(1) : '--'
    }
  } else {
    return '--'
  }
}

const foodTypeMash = (child: any, type: any) => {
  const value = (Number(child[type]) / 100) * Number(child.amount) * (child.ratio || 1)
  if (type == 'energy') {
    return Number(value.toFixed(0))
  } else {
    return Number(value.toFixed(1))
  }
}

// 浮动值 状态
const getFoodInfoStatus = (type: any, index: any) => {
  switch (type) {
    case 'energy':
      return recommendEnergy.value
        ? matchClassName(recommendEnergy.value, getFoodInfo('energy', index))
        : ''
    case 'cho':
      return recommendCho.value ? matchClassName(recommendCho.value, getFoodInfo('cho', index)) : ''
    case 'pro':
      return recommendPro.value ? matchClassName(recommendPro.value, getFoodInfo('pro', index)) : ''
    case 'fat':
      return recommendFat.value ? matchClassName(recommendFat.value, getFoodInfo('fat', index)) : ''
    default:
      return ''
  }
}

const matchClassName = (base: number, value: number) => {
  const floatPercent = ((value - base) / base) * 100
  const absFloatPercent = Math.abs(floatPercent)

  if (absFloatPercent <= 5) {
    return 'diet-num-normal'
  } else if (absFloatPercent <= 10) {
    return 'diet-num-warn'
  } else if (absFloatPercent > 10) {
    return 'diet-num-danger'
  } else {
    return ''
  }
}

// 时间段中的时间与当前时间对比
const getDayDisabled = (data: any) => {
  if (data.templateAffiliation == 'AI生成') {
    if (dayjs(data.cycleStart).add(data.activeKey, 'day').isSame(dayjs(), 'day')) {
      return false
    } else {
      return dayjs(data.cycleStart).add(data.activeKey, 'day').isBefore(dayjs())
    }
  } else {
    return props.isPushed
  }
}
</script>
<style lang="less" scoped>
.mana-plan-item-info {
  padding: 16px;
  border: 1px solid #e5e6eb;
}

.mana-plan-form .ant-form-item {
  margin-bottom: 12px;
}

.mana-plan-form .sprot-form .ant-form-item {
  margin-bottom: 18px;
}

.template-col {
  padding: 6px 20px;
  cursor: pointer;
  border: 1px solid #e5e5e5;
  border-radius: 2px;
}

.template-col.template-col-active {
  color: #165dff;
  background: #e8f3ff;
  border: 1px solid #165dff;
  border-radius: 2px 0 0 2px;
}

.dict-group {
  min-height: 42px;
  padding: 0 4px;
  border: 1px solid #d9d9d9;
}

.dict-name {
  display: inline-block;
  padding: 5px 8px;
  margin: 4px;
  color: #1d2129;
  background: #f2f3f5;
  border-radius: 2px;
}

.food-sub-name {
  font-size: 14px;
  color: #1d2129;
}

.food-weight {
  color: #165dff;
  cursor: pointer;
}

.dict-del-icon {
  margin-left: 4px;
  font-size: 12px;
  color: #4e5969;
  cursor: pointer;
}

.dict-btn {
  display: inline-block;
  padding: 5px 8px;
  margin: 4px;
  color: #165dff;
  cursor: pointer;
  background: #e8f3ff;
}

.season-row {
  margin-bottom: 12px;
}

.season-item {
  padding: 5px 16px;
  margin-right: 16px;
  font-size: 14px;
  color: #4e5969;
  cursor: pointer;
  background: #f7f8fa;
  border-radius: 100px;
}

.season-item-active {
  color: #165dff;
  background: #e8f3ff;
}

.week-row {
  display: flex;
  margin-bottom: 12px;
}

.week-item {
  color: #4e5969;
  cursor: pointer;
}

.week-item-active {
  color: #165dff;
}

.icon-add {
  margin-left: 4px;
}

.diet-info-box {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.diet-info {
  margin-right: 12px;
  font-size: 14px;
  font-weight: 400;
  color: #4e5969;
}

.diet-all {
  font-size: 14px;
  font-weight: 500;
  color: #1d2129;
}

.diet-num-normal {
  color: #00b42a;
}

.diet-num-warn {
  color: #ff7d00;
}

.diet-num-danger {
  color: #f53f3f;
}

.ai-state-icon {
  width: 20px;
  height: 20px;
  margin-right: 8px;
}

.mana-plan-time {
  display: flex;
  align-items: center;
  height: 40px;
  padding: 9px 12px;
  cursor: pointer;
  border: 1px solid #e5e6eb;
  border-radius: 4px 4px 0 0;

  .time-label {
    margin: 0 6px;
  }

  // .taskStatus {
  //   padding: 2px 6px;
  // }

  // .task-unPush {
  //   color: #f53f3f;
  //   background-color: #ffabab;
  // }

  // .task-push {
  //   color: #165dff;
  // }

  // .task-pushing {
  //   color: #ff7d00;
  // }
}

.mana-plan-time:hover {
  color: #69b1ff;
}

.mana-plan-task {
  padding: 0;
  border-width: 0;
}

.mana-plan-ai {
  padding: 16px;
  border: 1px solid #e5e6eb;
  border-top-width: 0;
}
</style>
